<!--

/*
* Copyright (C) 2005-2013 University of Sydney
*
* Licensed under the GNU License, Version 3.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/gpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/

/**
* brief description of file
*
* @author      Tom Murtagh
* @author      Kim Jackson
* @author      Ian Johnson   <ian.johnson@sydney.edu.au>
* @author      Stephen White   <stephen.white@sydney.edu.au>
* @author      Artem Osmakov   <artem.osmakov@sydney.edu.au>
* @copyright   (C) 2005-2013 University of Sydney
* @link        http://Sydney.edu.au/Heurist
* @version     3.1.0
* @license     http://www.gnu.org/licenses/gpl-3.0.txt GNU License 3.0
* @package     Heurist academic knowledge management system
* @subpackage  !!!subpackagename for file such as Administration, Search, Edit, Application, Library
*/

-->


<html>
 <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <link rel=stylesheet href="../../../common/css/global.css">
  <link rel=stylesheet href="../../../common/css/edit.css">
		<!--  <link rel=stylesheet href="../../../common/css/woot.css">    -->

  <script>
	function onshow() {}
	top.HAPI.importSymbols(top, this);
  </script>
  <script src="../../../external/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
  <script src="../../woot/woot.js"></script>

 </head>
 <body class="editTab" onload="onshow()">

  <form></form>

  <div>
   <h2>Extended text</h2>
   <span class="help prompt">WYSIWYG formatting and embedded links and images.<br>Note: Access rights can be set for individual paragraphs allowing personal notes which are visible only to you or which may be shared with your workgroups.
    </span>

			<div id=publicWoot></div>
   <a id=woot-ext-link target=_blank href="../../woot/woot.html">open in new window</a>
  </div>

  <div style="padding-top:10px; margin-top:20px; border-top: 1px solid #A4B4CB; ">
   <h2>Discussion</h2>
    <span class="help prompt">Threaded discussion of this record</span>

   <div id=comments></div>
  </div>

  <script>

			var installDir = function(){
				 var path = (top ? top.location.pathname : (window ? window.location.pathname : ""));
				 if ( path && path != "undefined") {
					path = path.match(/\/[^\s\/]\//);
					path = path ? path.replace(/\//g,"") : "";
					return path;
				 }
				 return "";
			}();


			function changed() { top.HEURIST.edit.changed("annotation"); }
			function unchanged() { top.HEURIST.edit.unchanged("annotation"); }

			document.forms[0].heuristForceSubmit = function() {
					if (wootEditor.unlockedChunk) {
						wootEditor.save();
					}

					for (var i in openComments) {
						openComments[i].save();
					}
			}


			// woot stuff
			var wootTitle = "record:" + top.HEURIST.edit.record.bibID;
			var recTitle = top.HEURIST.edit.record.title;

			document.getElementById("woot-ext-link").href += "?w=" + wootTitle + "&t=" + recTitle+ "&db="+top.HEURIST.database.name;

			HAPI.WOOT.GUI.labelsForLanguage.en.emptyMessage.label = "&lt;&lt; Empty or no visible text blocks &gt;&gt;";
			var wootEditor = new HAPI.WOOT.GUI.WootEditor({ title: wootTitle, element: document.getElementById("publicWoot") });


			// comments stuff

			var openComments = {};

			var Comment = function(parentComment, details) {
	this.document = parentComment.document;
	this.parentComment = parentComment;
	if (parentComment) {
		if (! parentComment.childComments) parentComment.childComments = [];
		parentComment.childComments.push(this);
	}
	this.details = details;

	this.id = details.id;

	this.div = parentComment.div.appendChild(document.createElement("div"));
		this.div.className = "comment";
	this.innerDiv = this.div.appendChild(this.document.createElement("div"));

	if (details.deleted) {
		this.innerDiv.className = "deleted";
		this.innerDiv.appendChild(this.document.createTextNode("(This comment has been deleted)"));
		this.div.style.display = "none";
		return;
	}
	if (parentComment.details  &&  parentComment.details.deleted) {
		parentComment.div.style.display = "";
	}

	this.innerDiv.className = "block";

	this.headerDiv = this.innerDiv.appendChild(this.document.createElement("div"));
		this.headerDiv.className = "header";
	this.author = this.headerDiv.appendChild(this.document.createElement("a"));
		this.author.className = "author";
		this.author.appendChild(this.document.createTextNode(details.user));
	if (details.added) {
		var date = this.headerDiv.appendChild(this.document.createElement("span"));
			date.className = "date";
			date.appendChild(this.document.createTextNode(this.formatDate(details.added)));
	}
	if (details.modified) {
		var modDate = this.headerDiv.appendChild(this.document.createElement("span"));
			modDate.className = "moddate";
			modDate.appendChild(this.document.createTextNode(" (modified " + this.formatDate(details.modified) + ")"));
	}

	var detailText = details.text || "";
		detailText = detailText.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
		detailText = detailText.replace(/(http:\/\/[\041-\176]+)/g, "<a href=\"$1\">$1</a>");
		detailText = detailText.replace(/\[(\d+)\]/g, "[<a href=\""+ installDir +"records/view/viewRecord.php?recID=$1\">$1</a>]");

	this.textDiv = this.innerDiv.appendChild(this.document.createElement("div"));
		this.textDiv.className = "text";
		this.textDiv.innerHTML = detailText;

	this.footerDiv = this.innerDiv.appendChild(this.document.createElement("div"));
		this.footerDiv.className = "footer";

		this.footerDiv.appendChild(this.document.createTextNode("("));
		this.replyLink = this.footerDiv.appendChild(this.document.createElement("a"));
			this.replyLink.href = "#";
			this.replyLink.appendChild(this.document.createTextNode("Reply to this"));
		this.footerDiv.appendChild(this.document.createTextNode(")"));

		var thisRef = this;
		this.replyLink.onclick = function() { thisRef.reply(); return false; };

	if (details.userID == top.HEURIST.get_user_id()) {
		this.footerDiv.appendChild(this.document.createTextNode(" ("));
		this.editLink = this.footerDiv.appendChild(this.document.createElement("a"));
			this.editLink.href = "#";
			this.editLink.appendChild(this.document.createTextNode("Edit"));
		this.footerDiv.appendChild(this.document.createTextNode(") "));

		var thisRef = this;
		this.editLink.onclick = function() { thisRef.edit(); return false; };

		this.footerDiv.appendChild(this.document.createTextNode(" ("));
		this.deleteLink = this.footerDiv.appendChild(this.document.createElement("a"));
			this.deleteLink.href = "#";
			this.deleteLink.appendChild(this.document.createTextNode("Delete"));
		this.footerDiv.appendChild(this.document.createTextNode(") "));

		this.deleteLink.onclick = function() { thisRef.remove(); return false; };
	}
			};
			Comment.prototype.edit = function() {
	var editComment = new EditableComment(this);
	this.div.replaceChild(editComment.innerDiv, this.innerDiv);
	editComment.textarea.focus();
			};
			Comment.prototype.reply = function() {
	var editComment = new EditableComment(null, this);

	// Put the editable reply immediately after the comment being replied to,
	// even though the eventual comment will be at the bottom
	if (! this.innerDiv.nextSibling) {
		this.div.appendChild(editComment.div);
	} else {
		this.div.insertBefore(editComment.div, this.innerDiv.nextSibling);
	}
	editComment.textarea.focus();
			};
			Comment.prototype.remove = function() {
	if (! confirm("Delete this comment?")) return;

	var fakeForm = { action: installDir + "records/comments/saveThreadedComments.php",
			elements: [
				{ name: "cmt_ID", value: this.id },
				{ name: "delete", value: 1 }
			] };
	var thisRef = this;

	top.HEURIST.util.xhrFormSubmit(fakeForm, function(json) {
		var vals = eval(json.responseText);

		if (vals  &&  vals.error) {
			alert("Error while deleting:\n" + vals.error);
			return;
		}

		thisRef.details.deleted = true;
		thisRef.div.removeChild(thisRef.innerDiv);

		thisRef.innerDiv = thisRef.document.createElement("div");
			thisRef.innerDiv.className = "deleted";
			thisRef.innerDiv.appendChild(thisRef.document.createTextNode("(This comment has been deleted)"));

		if (thisRef.div.firstChild)
			thisRef.div.insertBefore(thisRef.innerDiv, thisRef.div.firstChild);
		else
			thisRef.div.appendChild(thisRef.innerDiv);
	});
			};
			Comment.prototype.formatDate = function(date) {
	var date = new Date(Date.parse(date.replace(/-/g, "/")));
	var now = new Date(Date.parse(top.HEURIST.edit.record.retrieved.replace(/-/g, "/")));

	var dateTime = Math.round(date.getTime() / 1000);
	var nowTime = Math.round(now.getTime() / 1000);

	/* less than two hours ago */
	if ((nowTime - dateTime) <= 119*60) {
		var mins = Math.round((nowTime - dateTime) / 60);
		if (mins == 0) return "less than one minute ago";
		else if (mins == 1) return "1 minute ago";
		return mins + " minutes ago";
	}

	/* less than a day ago */
	if ((nowTime - dateTime) <= 23*60*60) {
		var hours = Math.round((nowTime - dateTime) / (60*60));
		return hours + " hours ago";
	}

	/* e.g. "yesterday 6:39pm" */
	if ((nowTime - dateTime) < 48*60*60  &&  now.getDay() == date.getDay()+1) {
		return "yesterday " + this.formatTime(date.getHours(), date.getMinutes());
	}

	/* less than a week ago -- e.g. "Tuesday 6:39pm" */
	if ((nowTime - dateTime) < 7*24*60*60) {
		return this.dayNames[date.getDay()] + " " + this.formatTime(date.getHours(), date.getMinutes());
	}

	/* this year */
	if (now.getFullYear() == date.getFullYear()) {
		return this.monthNames[date.getMonth()] + " " + date.getDate() + ", " + this.formatTime(date.getHours(), date.getMinutes());
	}

	/* else ... */
	return this.monthNames[date.getMonth()] + " " + date.getDate() + " " + date.getFullYear() + ", " + this.formatTime(date.getHours(), date.getMinutes());
			};
			Comment.prototype.formatTime = function(hours, minutes) {
	if (hours > 12)
		return (hours - 12) + ":" + minutes + "pm";
	else
		return hours + ":" + minutes + "am";
			};
			Comment.prototype.dayNames = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ];
			Comment.prototype.monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];

			var EditableComment = function(associatedComment, parentComment) {
	this.comment = associatedComment;

	if (associatedComment) {
		this.document = associatedComment.document;
		this.details = this.comment.details;
		this.id = this.details.id;
		this.parentComment = associatedComment.parentComment;
		this.div = associatedComment.div;
	} else {
		this.document = parentComment.document;
		this.details = {};
		this.id = 0;
		this.parentComment = parentComment;
		this.div = this.document.createElement("div");
		this.div.className = "comment";
	}
	this.innerDiv = this.document.createElement("div");
		this.innerDiv.className = "editing-block";

	if (! associatedComment) {
		this.div.appendChild(this.innerDiv);
	}

	this.textarea = this.innerDiv.appendChild(this.document.createElement("textarea"));
		this.textarea.value = this.textarea.defaultValue = this.details.text? this.details.text : "";
				//	var helpDiv = this.innerDiv.appendChild(this.document.createElement("div"));
				//		helpDiv.className = "help prompt";
				//		helpDiv.appendChild(this.document.createTextNode("Reference other records as [XXX] where XXX is the record number"));

	var thisRef = this;
	this.saveButton = this.document.createElement("input");
		this.saveButton.type = "button";
		this.saveButton.value = "Save edit";
		this.saveButton.onclick = function() { thisRef.save(); };
		this.innerDiv.appendChild(this.saveButton);

	this.cancelButton = this.document.createElement("input");
		this.cancelButton.type = "button";
		this.cancelButton.value = "Cancel edit";
		this.cancelButton.onclick = function() { thisRef.cancel(); return false; };
		this.innerDiv.appendChild(this.cancelButton);

	this.deleteButton = this.document.createElement("input");
		this.deleteButton.type = "button";
		this.deleteButton.value = "Delete comment";
		this.innerDiv.appendChild(this.deleteButton);

	do {
		this.nonce = Math.floor(Math.random() * 1000000);
	} while (openComments[this.nonce]);
	openComments[this.nonce] = this;
			};
			EditableComment.prototype.save = function() {
	if (this.textarea.value == "") {
		// Don't bother saving an empty input
		this.cancel();
		return;
	}

	var fakeForm = { action: installDir + "records/comments/saveThreadedComments.php",
			elements: [
				{ name: "cmt_ID", value: this.id },
				{ name: "recID", value: parent.HEURIST.edit.record.bibID },
				{ name: "owner",  value: this.parentComment.id },
				{ name: "text",   value: this.textarea.value }
			] };
	var thisRef = this;

	top.HEURIST.util.xhrFormSubmit(fakeForm, function(json) {
		var vals = eval(json.responseText);
		if (! vals) return;

		if (vals.error) {
			alert("Error while saving:\n" + vals.error);
		} else if (vals.comment) {
			newComment = new Comment(thisRef.parentComment, vals.comment);
			if (thisRef.comment) {
				// replace this new comment where the old one was
				thisRef.div.parentNode.replaceChild(newComment.div, thisRef.div);
			} else {
				thisRef.div.parentNode.removeChild(thisRef.div);
			}

			newComment.replyLink.focus();
			newComment.author.focus();

			delete openComments[thisRef.nonce];
		}
	});
			}
			EditableComment.prototype.cancel = function() {
	if (this.comment) {
		/* replace this editable comment with the plain comment that it replaced */
		this.div.replaceChild(this.comment.innerDiv, this.innerDiv);
	} else {
		this.div.parentNode.removeChild(this.div);
	}

	delete openComments[thisRef.nonce];
			};


			function printAllComments() {
	var commentDetails = top.HEURIST.edit.record.comments;
	var comments = {};

	var commentsDiv = document.getElementById("comments");
	var topLevelComment = { document: document, id: 0, div: commentsDiv };
		comments[0] = topLevelComment;

	var commentLink = document.createElement("a");
		commentLink.href = "#";
		commentLink.id = "comment-link";
		commentLink.appendChild(document.createTextNode("Add comment"));
		commentLink.onclick = function() {
			var editComment = new EditableComment(null, topLevelComment);
			commentLink.parentNode.insertBefore(editComment.div, commentLink.nextSibling);
			editComment.textarea.focus();
			return false;
		};
	commentsDiv.appendChild(commentLink);

	for (var cmtID in commentDetails) {
		var commentDetail = commentDetails[cmtID];

		if (!commentDetail.owner) {
			comments[cmtID] = new Comment(topLevelComment, commentDetail);
		}else if (comments[commentDetail.owner]) {
			comments[cmtID] = new Comment(comments[commentDetail.owner], commentDetail);
		}else {	/* ownerless comment is just a stub for grouping -- deprecated */
			comments[cmtID] = topLevelComment;
		}
	}
			}

			printAllComments();

		</script>

 </body>
</html>
